# -*- coding:UTF-8 -*-
import os
import sys
import tkinter
from tkinter import filedialog, Frame
from tkinter import scrolledtext
from tkinter.constants import END, RAISED

import zxing

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import uutil.util_file_read

call_result = {'file_name': '', 'message': ''}


class MessageBox(Frame):
    """
    消息弹窗
    """

    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.message = None
        self.text = None

    def __cent_message_window(self, width=600, height=100):
        print('__cent_message_window start')
        w_s = root.winfo_screenwidth()
        h_s = root.winfo_screenheight()
        x = (w_s / 2) - (width / 2)
        y = (h_s / 2) - (height / 2) + 200
        self.message.geometry("%dx%d+%d+%d" % (width, height, x, y))
        print('__des stop')

    def show_message(self):
        """
        弹窗信息
        """
        self.message = tkinter.Tk(className='message')
        self.__cent_message_window()
        self.text = tkinter.Text(self.message, width=57, height=8)
        self.text.grid(row=0, column=0, padx=10, pady=10)
        self.text.insert(END, call_result['message'])
        self.mainloop()


class SelectFile(Frame):
    """
    文件选择框
    """

    def __init__(self, parent=None):
        print('__init__ start')
        Frame.__init__(self, parent)
        self.btn_submit = None
        self.entry_file = None
        self.btn_select = None
        self.file = None
        self.file_name = None
        print('__init__ stop')

    def __select_box(self):
        print('__select_box start')
        askopenfilename = filedialog.askopenfilename()
        # messagebox.showinfo('选择文件', askopenfilename)
        self.entry_file.insert(END, askopenfilename)
        self.file_name = askopenfilename
        print('__select_box stop')

    def __des(self):
        print('__des start')
        # call_result['file_name'] = self.file_name
        self.file.quit()
        print('__des stop')
        self.file.destroy()

    def __cent_select_window(self, w=600, h=100):
        print('__cent_select_window start')
        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2) + 200
        self.file.geometry("%dx%d+%d+%d" % (w, h, x, y))
        print('__des stop')

    def select_file(self):
        """
        选择文件
        """
        print('select_file start')
        self.file = tkinter.Tk(className='select')
        self.__cent_select_window()
        self.btn_select = tkinter.Button(self.file, text='点击选择文件：',
                                         width=14, height=1,
                                         relief=RAISED, command=self.__select_box)
        self.btn_select.grid(row=0, column=0, padx=10, pady=10)
        self.entry_file = tkinter.Entry(self.file, width=60)
        self.entry_file.grid(row=0, column=1, padx=10, pady=10)
        self.btn_submit = tkinter.Button(self.file, text='submit',
                                         width=14, height=1,
                                         relief=RAISED, command=self.__des)
        self.btn_submit.grid(row=1, column=0, padx=10, pady=10)
        self.mainloop()
        print('select_file stop')
        return self.file_name


def message():
    """
    消息弹窗
    """
    box = MessageBox(root)
    box.show_message()


def select():
    """
    文件选择
    """
    print('select start')
    select_file_window = SelectFile(root)
    file = select_file_window.select_file()
    file_entry.insert(END, file)
    print('select stop')
    call_result['file_name'] = file


def excel_to_markdown():
    """
    excel转markdown
    """
    try:
        count = 0
        xlsx = uutil.util_file_read.read_xlsx(call_result['file_name'])
        for row in xlsx:
            row_len = len(row)
            if count == 1:
                for tl in range(row_len):
                    excel_text.insert(END, '|---')
                excel_text.insert(END, '|\n')
            for rl in range(row_len):
                cell = row[rl]
                value = cell.value
                if value is None:
                    value = 'none'
                excel_text.insert(END, '|')
                excel_text.insert(END, value)
            excel_text.insert(END, '|\n')
            count = count + 1
    except Exception as result:
        call_result['message'] = str(result)
        print(result)
        message()


def encode_qrcode():
    """
    二维码识别
    """
    try:
        file_name = call_result['file_name']
        reader = zxing.BarCodeReader()
        decode = reader.decode(file_name)
        parsed = decode.parsed
        qrcode_text.insert(END, parsed)
    except Exception as result:
        call_result['message'] = str(result)
        print(result)
        message()


def main_quit():
    """
    主界面退出
    """
    root.quit()
    root.destroy()


def center_window(w=550, h=300):
    """
    主界面
    """
    print('center_window start')
    w_s = root.winfo_screenwidth()
    h_s = root.winfo_screenheight()
    x = (w_s / 2) - (w / 2)
    y = (h_s / 2) - (h / 2)
    root.geometry("%dx%d+%d+%d" % (w, h, x, y))
    print('center_window stop')


if __name__ == '__main__':
    print(sys.path)
    print('main start')
    root = tkinter.Tk(className='python gui')
    center_window()
    select_btn = tkinter.Button(root, text='选择文件：',
                                width=8, height=1,
                                relief=RAISED, command=select)
    select_btn.grid(row=0, column=0, padx=10, pady=10)
    excel_btn = tkinter.Button(root, text='excel转markdown',
                               width=8, height=5,
                               relief=RAISED, command=excel_to_markdown)
    excel_btn.grid(row=1, column=0, padx=10, pady=10)
    image_base64_btn = tkinter.Button(root, text='二维码识别',
                                      width=8, height=5,
                                      relief=RAISED, command=encode_qrcode)
    image_base64_btn.grid(row=2, column=0, padx=10, pady=10)
    file_entry = tkinter.Entry(root, width=60)
    file_entry.grid(row=0, column=1, padx=10, pady=10)
    excel_text = scrolledtext.ScrolledText(root, width=57, height=8)
    excel_text.grid(row=1, column=1, padx=10, pady=10)
    qrcode_text = scrolledtext.ScrolledText(root, width=57, height=8)
    qrcode_text.grid(row=2, column=1, padx=10, pady=10)
    root.mainloop()
    print('main stop')
